import 'package:flutter_blue_plus/flutter_blue_plus.dart';
import 'package:realm/realm.dart';
import 'package:sgy_flutter/ble/HardwareVersion.dart';
import 'package:sgy_flutter/ble/ext.dart';
import 'package:sgy_flutter/database/device_entity.dart';
import 'package:sgy_flutter/model/device_type.dart';

import 'product_type.dart';

class DeviceModel {
  final String name;
  final String address;

  String? hardware;
  String? firmware;
  DeviceModel? rightDeviceModel;
  bool inTransportMode = false;
  final String? deviceSN;
  final String? deviceID;
  final num? rssi;
  final bool? connected;
  bool isDoubleSlide;

  DeviceModel({
    required this.name,
    required this.address,
    this.hardware,
    this.firmware,
    this.rightDeviceModel,
    this.deviceSN,
    this.rssi,
    this.connected,
    this.deviceID,
    this.isDoubleSlide = false,
    this.inTransportMode = false,
  });

  ProductType get productType => ProductType.fromDeviceType(deviceType);

  double get firmwareNumber {
    return double.tryParse(
            (firmware ?? '').replaceAll(RegExp('[^0-9.]'), '')) ??
        double.maxFinite;
  }

  int get deviceIdNumber {
    return int.tryParse((deviceID ?? '').replaceAll(RegExp('[^0-9]'), '')) ?? 0;
  }

  /**
   * 根据硬件版本号来判断是否是新设备
   */
  bool get isNewDevice {
    return hardware?.startsWith(HardwareVersion.AXO_2_0.value) == true ||
        hardware?.startsWith(HardwareVersion.DLS_1_0.value) == true ||
        hardware?.startsWith(HardwareVersion.JT_1_0.value) == true;
  }

  bool get isAxo {
    return deviceType == DeviceType.axo;
  }

  bool get isDls {
    return deviceType == DeviceType.dlsL || deviceType == DeviceType.dlsR;
  }

  DeviceType get deviceType => DeviceType.fromDeviceName(name);

  factory DeviceModel.fromEntity(RealmDeviceEntity entity) {
    return DeviceModel(
        name: entity.name,
        address: entity.address,
        deviceID: entity.deviceID,
        deviceSN: entity.deviceSN,
        hardware: entity.hardware,
        firmware: entity.firmware,
        isDoubleSlide: entity.isDoubleSlide);
  }

  /**
   * 广播自定义数据
   * 新AXO 0-7 序列号 8运输模式状态
      新DLS 0-7 序列号 8单双边9 运输模式
      旧AXO 0运输模式
      旧DLS 0运输模式
   */
  factory DeviceModel.fromScanResult(ScanResult result) {
    bool isDoubleSlide = false;
    bool inTransportMode = false;
    String? productSn;
    print(
        "扫描:${result.device.platformName},${result.device.advName}:${result.advertisementData.msd.map((entity) => "${entity.toHex(':')}").join("\n")}");
    for (var entity in result.advertisementData.msd) {
      if (result.device.platformName.startsWith("DLS")) {
        //DLS 有他的特殊性
        if (entity.length == 8){
          if (entity.first != 0xff) {
            final flag = String.fromCharCodes([entity.first]);
            // print("DeviceModel: DLS 标志位:${flag}");
            if (flag == "T") {
              isDoubleSlide = true;
            }
            if (flag == "S") {
              isDoubleSlide = false;
            }
          }

          if (entity.length > 1) {
            productSn = entity
                .sublist(1)
                .map((e) => e == 0xff ? "0" : String.fromCharCodes([e]))
                .join();
          }
        }
        else if (entity.length == 2){
          inTransportMode = entity[0] == 0x01;
        }else if (entity.length == 9){
          productSn = entity
              .sublist(0, 6)
              .map((e) => e == 0xff ? "0" : String.fromCharCodes([e]))
              .join();
          final flag = String.fromCharCodes([entity[7]]);
          // print("DeviceModel: DLS 标志位:${flag}");
          if (flag == "T") {
            isDoubleSlide = true;
          }
          if (flag == "S") {
            isDoubleSlide = false;
          }
          inTransportMode = entity[8] == 0x01;
        }

      }if (result.device.platformName.startsWith("AXO")) {
        if (entity.length == 2){
          inTransportMode = entity[0] == 0x01;
        }else if (entity.length == 8){
          productSn = entity
              .sublist(0, 6)
              .map((e) => e == 0xff ? "0" : String.fromCharCodes([e]))
              .join();
          inTransportMode = entity[7] == 0x01;
        }else{
          productSn = entity
              .map((e) => e == 0xff ? "0" : String.fromCharCodes([e]))
              .join();
        }

      } else {
        // productSn = String.fromCharCodes([entity.key]);
        productSn = entity
            .map((e) => e == 0xff ? "0" : String.fromCharCodes([e]))
            .join();
      }
    }

    var deviceId = result.device.platformName;
    deviceId = deviceId.replaceAll("AXO_PWR", "");
    for (var type in DeviceType.values) {
      deviceId = deviceId.replaceAll(type.prefix, "");
    }
    deviceId = deviceId.replaceAll("_", "");
    print("deviceId:${deviceId},inTransportMode:${inTransportMode}");
    return DeviceModel(
        name: result.device.platformName,
        address: result.device.remoteId.str,
        deviceID: deviceId,
        deviceSN: productSn,
        isDoubleSlide: isDoubleSlide,
        inTransportMode: inTransportMode,
        rssi: result.rssi);
  }

  /**
   * 注意ObjectID
   */
  RealmDeviceEntity toEntity({ObjectId? id = null}) {
    return RealmDeviceEntity(id ?? ObjectId(), name, address, isDoubleSlide,
        hardware: hardware,
        firmware: firmware,
        deviceSN: deviceSN,
        deviceID: deviceID);
  }

  /**
   * 判断是否是一对，规则为，DLS_L的设备ID+1等于DLS_R的设备ID
   * @param productModel ProductModel
   * @return Boolean
   */
  bool isRightDevice(DeviceModel otherModel) {
    if (otherModel.name.contains("R") && otherModel.productType == ProductType.dls) {
      if (productType == otherModel.productType) {
        final left = deviceIdNumber;
        final right = otherModel.deviceIdNumber;
        final isRight = left + 1 == right;
        if (isRight && rightDeviceModel == null) {
          rightDeviceModel = otherModel;
        }
        return isRight;
      }
    }
    return false;
  }

  /**
   * 判断是否是一对，规则为，DLS_L的设备ID+1等于DLS_R的设备ID
   * @param productModel ProductModel
   * @return Boolean
   */
  bool isLeftDevice(DeviceModel otherModel) {
    if (otherModel.name.contains("L") && otherModel.productType == ProductType.dls) {
      if (productType == otherModel.productType) {
        final right = deviceIdNumber;
        final left = otherModel.deviceIdNumber;
        final isRight = left + 1 == right;
        if (isRight && rightDeviceModel == null) {
          rightDeviceModel = otherModel;
        }
        return isRight;
      }
    }
    return false;
  }

  /**
   * 过滤掉右边的设备
   */
  static List<DeviceModel> filterRightPart(List<DeviceModel> list) {
    List<DeviceModel> items = List.empty(growable: true);

    for (final other in list) {
      var notTheRightPart = true;
      for (final deviceModel in list) {
        if (deviceModel.isRightDevice(other)) {
          notTheRightPart = false;
          break;
        }
      }
      if (notTheRightPart) {
        items.add(other);
      }
    }
    return items;
  }

  DeviceModel copyWith({
    String? name,
    String? address,
    String? hardware,
    String? firmware,
    DeviceModel? rightDeviceModel,
    String? deviceSN,
    num? rssi,
    bool? connected,
    String? deviceID,
    bool? inTransportMode,
  }) {
    return DeviceModel(
      name: name ?? this.name,
      address: address ?? this.address,
      hardware: hardware ?? this.hardware,
      firmware: firmware ?? this.firmware,
      rightDeviceModel: rightDeviceModel ?? this.rightDeviceModel,
      deviceSN: deviceSN ?? this.deviceSN,
      deviceID: deviceID ?? this.deviceID,
      rssi: rssi,
      connected: connected ?? this.connected,
      isDoubleSlide: isDoubleSlide,
      inTransportMode: inTransportMode?? this.inTransportMode,
    );
  }

  @override
  String toString() {
    return 'DeviceModel{name: $name, address: $address, hardware: $hardware, firmware: $firmware, rightDeviceModel: $rightDeviceModel, deviceSN: $deviceSN, deviceID: $deviceID, rssi: $rssi, connected: $connected, isDoubleSlide: $isDoubleSlide}';
  }
}
